
import rules from './validateRules'
import i18n from '@/lang'

const validate = {}
validate.install = function(Vue, options) {
  const validateRules = (rule, value, callback) => {
    if (value && value !== '') {
      const fName = rule.item.key
      const fParam = rule.item.param
      const info = rules[fName](value, fParam)
      if (info.result === false) {
        callback(new Error(info.message))
      } else {
        callback()
      }
    } else {
      callback()
    }
  }
  Vue.prototype.filter_rules = function(options, trigger) {
    const rulesTmp = []
    let item = {}
    if (options && typeof options === 'string' && options.indexOf('{') === 0 && options.indexOf('}') === options.length - 1) {
      item = JSON.parse(options)
    } else {
      item = options
    }
    for (const key in item) {
      if (key === 'required') {
        rulesTmp.push({ required: true, trigger: trigger || 'blur', message: i18n.t('va.required') })
        // rulesTmp.push({ validator: validateRules, trigger: trigger || 'blur', item: { key: 'empty', param: true }})
      } else if (rules[key]) {
        rulesTmp.push({ validator: validateRules, trigger: trigger || 'blur', item: { key: key, param: item[key] }})
      }
    }

    return rulesTmp
  }
  Vue.prototype.validate = function(value, options) {
    let item = {}
    if (!options) {
      return ''
    }
    if (options && options.indexOf('{') === 0 && options.indexOf('}') === options.length - 1 && typeof options === 'string') {
      item = JSON.parse(options)
    } else {
      item = options
    }
    if (value === '' && (!item.required || item.required === false)) {
      return ''
    }
    const result = []
    for (const key in item) {
      if (rules[key]) {
        const tmp = rules[key](value, item[key])
        if (!tmp.result) {
          result.push(tmp.message)
          break
        }
      }
    }
    return result.join(';')
  }
}
export default validate
